package com.helloDemo.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.helloDemo.domain.User;
import com.helloDemo.server.UserServer;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UserRealm extends AuthorizingRealm {

	@Autowired
	private UserServer userServer;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		log.info("执行授权逻辑");

		// 给资源进行授权
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

		// 添加资源的授权字符串
		// info.addStringPermission("user:add");

		// 获取当前用户
		Subject subject = SecurityUtils.getSubject();

		User user = (User) subject.getPrincipal();

		User dbUser = userServer.findById(user.getId());

		info.addStringPermission(dbUser.getPerms());

		return info;

	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		log.info("执行认证逻辑");
		// System.out.println("执行认证逻辑");

		// String dbusername = "admin";

		// String dbpassword = "admin";

		// 判断用户名
		UsernamePasswordToken tokenNp = (UsernamePasswordToken) token;

		String username = tokenNp.getUsername();

		// 查询数据库
		User userDb = userServer.findByUserName(username);

		log.info(userDb.toString());

		boolean equals = tokenNp.getUsername().equals(userDb.getUsername());

		if (!equals) {

			// 用户名不存在
			// shiro 底层会抛出UnknownAccountException
			return null;

		}
		// 2.判断密码
		return new SimpleAuthenticationInfo(userDb, userDb.getPassword(), "");
	}

}
